package cn.haoma.base.utils;


import android.content.Context;
import android.content.SharedPreferences;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;

import java.util.Random;
import java.util.UUID;

public class DeviceUtil {
    private static int width;
    private static int height;
    private static float density;
    private static boolean isInited = false;
    private static SharedPreferences sp;
    private static Context context;

    public static int dip2px(float dpValue) {
        return (int) (dpValue * density + 0.5f);
    }

    /**
     * @return 屏幕高度
     */
    public static int getHeight() {
        return height;
    }

    public static String getUUID() {
        return new UUID(System.currentTimeMillis(), getDeviceId().hashCode()).toString();
    }

    public static String getDeviceId() {
        return getUniqueID();
    }

    // public static Context _context;
    private static String getUniqueID() {
        if (sp != null) {
            String devicieId = sp.getString("DevicieId", "");
            if (devicieId.equals("")) {
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                String _id = tm.getDeviceId();
                devicieId = MD5Util.getMD5Str(_id.getBytes()).toLowerCase();
            }
            if (devicieId.equals("")) {
                Object saveId = ObjUtil.get("DeviceId");
                if (saveId != null) {
                    devicieId = (String) saveId;
                } else {
                    Random r = new Random();
                    devicieId = System.currentTimeMillis() + "" + r.nextInt(Integer.MAX_VALUE);
                    ObjUtil.save("DeviceId", devicieId);
                }
            }
            sp.edit().putString("DeviceId", devicieId).commit();
            return devicieId;
        } else {
            return "";
        }

    }

    /**
     * @return 屏幕宽度
     */
    public static int getWidth() {
        return width;
    }

    public static void init(Context c) {
        if (isInited) return;
        isInited = true;
        context = c.getApplicationContext();
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        sp = context.getSharedPreferences("Device", Context.MODE_PRIVATE);
        height = dm.heightPixels;
        width = dm.widthPixels;
        density = dm.density;
        //		deviceId = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
    }

    public static int px2dip(float pxValue) {
        return (int) (pxValue / density + 0.5f);
    }


}